package cn.wolfcode.luowowo.website.controller;

import cn.wolfcode.luowowo.article.domain.SiteCollect;
import cn.wolfcode.luowowo.article.domain.StrategyDetail;
import cn.wolfcode.luowowo.article.domain.Travel;
import cn.wolfcode.luowowo.article.domain.Viewpoint;
import cn.wolfcode.luowowo.article.service.IDestinationService;
import cn.wolfcode.luowowo.article.service.ISiteCollectService;
import cn.wolfcode.luowowo.article.service.IStrategyDetailService;
import cn.wolfcode.luowowo.article.service.ITravelService;
import cn.wolfcode.luowowo.article.vo.TravelInfo;
import cn.wolfcode.luowowo.cache.service.IStrategyStatsCacheService;
import cn.wolfcode.luowowo.cache.service.ITravelStatsCacheService;
import cn.wolfcode.luowowo.cache.service.IUserInfoCacheService;
import cn.wolfcode.luowowo.cache.service.IVerifyCodeCacheService;
import cn.wolfcode.luowowo.cache.vo.ConcernStats;
import cn.wolfcode.luowowo.comment.domain.TravelComment;
import cn.wolfcode.luowowo.comment.service.ITravelCommentService;
import cn.wolfcode.luowowo.common.query.TravelQueryObject;
import cn.wolfcode.luowowo.common.util.AjaxResult;
import cn.wolfcode.luowowo.common.util.Consts;
import cn.wolfcode.luowowo.member.domain.UserInfo;
import cn.wolfcode.luowowo.member.service.IUserInfoService;
import cn.wolfcode.luowowo.website.annotation.LoginUser;
import cn.wolfcode.luowowo.website.annotation.RequireLogin;
import cn.wolfcode.luowowo.website.util.UploadUtil;
import com.alibaba.fastjson.JSON;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.*;



@Controller
@RequestMapping("mine")
public class MineController {
    @Reference
    private ITravelService travelService;
    @Reference
    private IDestinationService destinationService;
    @Reference
    private ITravelCommentService travelCommentService;
    @Reference
    private IUserInfoService userInfoService;
    @Reference
    private IUserInfoCacheService userInfoCacheService;
    @Reference
    private IVerifyCodeCacheService verifyCodeCacheService;
    @Reference
    private ITravelStatsCacheService travelStatsCacheService;
    @Reference
    private ISiteCollectService siteCollectService;
    @Reference
    private IStrategyStatsCacheService strategyStatsCacheService;
    @Reference
    private IStrategyDetailService strategyDetailService;

    @RequireLogin
    @RequestMapping("home")
    public Object home(@LoginUser UserInfo user, Model model, TravelQueryObject qo){
        //查询个人信息
        model.addAttribute("u",user);
        //查询我的游记
        /*qo.setUserId(user.getId());
        qo.setOrderBy("t.thumbsupnum DESC");
        PageInfo<Travel> query = travelService.query(qo);*/

        List<Travel> travels = travelService.selectByUserId(user.getId());
        model.addAttribute("sum",travels.size());
        travels = travels.size()<3 ? travels : travels.subList(0, 2);
        model.addAttribute("travels",travels);
        //通过用户id查询游记回复
        List<TravelComment> comments = travelCommentService.findByUserId(user.getId());
        model.addAttribute("count",comments.size());
        model.addAttribute("comments",comments);
        //我的关注
        List<ConcernStats> concerns = userInfoCacheService.getConcerns(user.getId());
        model.addAttribute("concerns",concerns);
        //关注数量
        int num = concerns == null ? 0:concerns.size();
       model.addAttribute("concernsNum",num);
        //粉丝数
        model.addAttribute("fensNum",userInfoCacheService.getFensNum(user.getId()));
        model.addAttribute("currentMineNav","home");
        //通过游记id查询游记数量
        return "mine/homepage";
    }

    @RequestMapping("travels")
    @RequireLogin
    public Object travels(@LoginUser UserInfo user, Model model, TravelQueryObject qo) throws Exception {

        model.addAttribute("currentMineNav","travels");
        model.addAttribute("u",user);
        List<Travel> travels = travelService.selectByUserId(user.getId());
        int totalTravel = travels.size();
        int totalReply=0;
        int totalView=0;
        model.addAttribute("sum", totalTravel);
        model.addAttribute("travels",travels);
        //查询总游记量和总计回复和总计阅读
        String name =null;
        ArrayList<Integer> list = new ArrayList<>();
        for (Travel travel : travels) {
            totalReply=travel.getReplynum()+totalReply;
            totalView=travel.getViewnum()+totalView;
        }
        TravelInfo travelInfo = new TravelInfo(totalTravel, totalReply, totalView);
        model.addAttribute("travelInfo",travelInfo);
        //累计访客
        model.addAttribute("allVisitor",userInfoCacheService.getAllVisitorNum(user.getId()));
        //今日访客
        model.addAttribute("todayVisitor",userInfoCacheService.getTodayVisitorNum(user.getId()));
        return "mine/mytravelnotes";
    }

    @RequestMapping("reviews")
    @RequireLogin
    public Object reviews(@LoginUser UserInfo user, Model model, TravelQueryObject qo){
        model.addAttribute("currentMineNav","reviews");
        model.addAttribute("u",user);
        //通过用户id查询游记回复
        List<TravelComment> comments = travelCommentService.findByUserId(user.getId());
        model.addAttribute("count",comments.size());
        model.addAttribute("comments",comments);
        return "mine/review";
    }
    @RequestMapping("insertViewId")
    @ResponseBody
    @RequireLogin
    public AjaxResult insertViewId(@LoginUser UserInfo user,Long viewId){
        AjaxResult result = new AjaxResult();
        if(viewId!=null){
            SiteCollect record = new SiteCollect();
            record.setUserId(user.getId());
            record.setViewId(viewId);
            siteCollectService.save(record);
            return result;
        }else {
            result.mark("沒有收藏");
            return result;
        }
    }
    @RequestMapping("collections")
    @RequireLogin
    public Object collections(@LoginUser UserInfo user, Model model, TravelQueryObject qo,Long viewId){
        //通过用户的id查询收藏的景点
        List<Viewpoint>viewPorts= siteCollectService.selectViewPointByUserId(user.getId());
        model.addAttribute("viewPorts",viewPorts);
        model.addAttribute("u",user);
        model.addAttribute("currentMineNav","collections");


        //通过用户id查询攻略ids
        List<Long> strategyIds = strategyStatsCacheService.listStrategiesByUserId(user.getId());
        List<StrategyDetail> strategyVos = new ArrayList<>();
        if(strategyIds!=null){
            for (Long id : strategyIds) {
                StrategyDetail strategyDetail = strategyDetailService.selectById(id);
                strategyVos.add(strategyDetail);
            }
        }
        model.addAttribute("strategyVos",strategyVos);

        //通过用户id查询游记ids
        List<Long> travelIds = travelStatsCacheService.listTravelsByUserId(user.getId());
        List<Travel> travels = new ArrayList<>();
        if(travelIds!=null){
            for (Long travelId : travelIds) {
                Travel travel = travelService.selectById(travelId);
                travels.add(travel);
            }
        }
        model.addAttribute("travels",travels);
        return "mine/travelcollection";
    }


    @RequestMapping("setting")
    @RequireLogin
    public Object setting(@LoginUser UserInfo user, Model model){
        model.addAttribute("currentMineNav","setting");
        //查询用户信息共享数据
        model.addAttribute("u",user);
        return "mine/setting";
    }

    @RequestMapping("update")
    @ResponseBody
   // @RequireLogin
    public void update( UserInfo user,HttpServletResponse response,HttpSession session) throws IOException {
        //修改用户
        AjaxResult result = userInfoService.updateBaseInfo(user);
        //修改成功,返回token给用户
        if (result.isSuccess()){
            //通过cookie返回去
            String token = (String) result.getData();
            Cookie cookie = new Cookie(Consts.USER_INFO_TOKEN,token);
            response.addCookie(cookie);
            //将用户信息存入session中
            String userInfo = userInfoCacheService.getUserInfo(token);
            session.setAttribute(Consts.USER_INFO,JSON.parseObject(userInfo, UserInfo.class));//将json解析成java对象
        }

        response.sendRedirect("/mine/setting");
    }

    @Value("${file.dir}")
    private String filePath;

    @RequestMapping("file")//上传头像
    @ResponseBody
    public Object file(MultipartFile files,@LoginUser UserInfo user){
        String upload = UploadUtil.upload(files, filePath);
        user.setHeadImgUrl("/"+upload);
        AjaxResult result = userInfoService.updateHeadImg(user);
        System.out.println(upload);
        return result;
    }

    //修改密码,手机验证
    @RequestMapping("phone")//上传头像
    public Object phone(@LoginUser UserInfo user){
        //向手机发送验证码
        String verifyCode = verifyCodeCacheService.getVerifyCode(user.getPhone());
        verifyCode = UUID.randomUUID().toString().substring(0, 4);
        System.err.println("亲,您的验证码是"+ verifyCode + "请在60s内使用");
        //缓存验证码
        verifyCodeCacheService.setVerifyCode(user.getPhone(),verifyCode);
        return "mine/view-source";//跳转到验证页面
    }

    //修改手机号码原来的手机号
    @RequestMapping("oldPhone")
    @ResponseBody
    public AjaxResult oldPhone(String phone,@LoginUser UserInfo user){
        AjaxResult result = new AjaxResult();
        if(user.getPhone().equals(phone)){
            //产生验证码
            String verifyCode = verifyCodeCacheService.getVerifyCode(user.getPhone());
            verifyCode = UUID.randomUUID().toString().substring(0, 4);
            System.err.println("亲,您的验证码是"+ verifyCode + "请在60s内使用");
            //缓存验证码
            verifyCodeCacheService.setVerifyCode(user.getPhone(),verifyCode);
            return result;
        }else {
            return result.mark("手机号码错误");

        }
    }
    //旧的验证码
    @RequestMapping("code")
    @ResponseBody
    public AjaxResult code(String phone,String code,@LoginUser UserInfo user){
        AjaxResult result = new AjaxResult();
        String verifyCode = verifyCodeCacheService.getVerifyCode(user.getPhone());
        if (user.getPhone().equals(phone)&& code.equals(verifyCode)) {
            return result;
        }else {
            return result.mark("手机号或者验证码不正确");
        }

    }

    //修改手机号码新的手机号
    @RequestMapping("newPhone")
    @ResponseBody
    public AjaxResult newPhone(String phone){
        AjaxResult result = new AjaxResult();
        UserInfo userInfo=userInfoService.selectByPhone(phone);

            if (userInfo!=null){
                return result.mark("手机号已经存在");
            }else {
                //产生验证码
                String verifyCode = verifyCodeCacheService.getVerifyCode(phone);
                verifyCode = UUID.randomUUID().toString().substring(0, 4);
                System.err.println("亲,您的验证码是"+ verifyCode + "请在60s内使用");
                //缓存验证码
                verifyCodeCacheService.setVerifyCode(phone,verifyCode);
            }

        return result;
    }

    //新的验证码
    @RequestMapping("newCode")
    @ResponseBody
    public AjaxResult newCode(String phone,String code,@LoginUser UserInfo user){
        AjaxResult result = new AjaxResult();
        String verifyCode = verifyCodeCacheService.getVerifyCode(phone);
        if(code.equals(verifyCode)){
            user.setPhone(phone);
            userInfoService.updatePhone(user);
            return result;
        }else {
            return result.mark("验证码不正确");
        }
    }

    //验证验证码是否正确,若是正确修改密码,重新登录
    @RequestMapping("mobile")
    @ResponseBody
    public Object mobile(@LoginUser UserInfo user,String password,String rpassword,String smscode){
        AjaxResult result = userInfoService.updatePassword(user, password, rpassword, smscode);
        return result;
    }


    /**
     * 点击关注他人,要求登录
     * @return
     */
    @RequestMapping("concern")
    @ResponseBody
    @RequireLogin
    public Object concern(UserInfo concern,@LoginUser UserInfo user){
        //封装信息
        concern = new UserInfo();
        concern.setId(2L);
        concern.setHeadImgUrl("/images/default.png");
        concern.setNickname("bunny");
        ConcernStats vo = new ConcernStats();
        vo.setUserId(concern.getId());
        vo.setNickname(concern.getNickname());
        vo.setHeadUrl(concern.getHeadImgUrl());

        //缓存关注者信息
        AjaxResult result = userInfoCacheService.addConcern(vo,user.getId());

        System.err.println(result);

        return result;
    }

}
